import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/home_page/subject_tab_component/item/state.dart';

import 'action.dart';
import 'state.dart';

Reducer<SubjectListState> buildReducer() {
  return asReducer(
    <Object, Reducer<SubjectListState>>{
      SubjectListAction.loaded: _loaded,
      SubjectListAction.loading: _loading,
      SubjectListAction.listResult: _listResult,
      SubjectListAction.deleted: _deleted,
    },
  );
}

/// self 说明
/// 由于有两个相同的component，reducer时会给两边都发，所以用self判断是否该处理

SubjectListState _loading(SubjectListState state, Action action) {
  bool self = action.payload['self'];
  if (self != state.self) {
    return state;
  }

  return state.clone()..isLoading = true;
}

SubjectListState _loaded(SubjectListState state, Action action) {
  bool self = action.payload['self'];
  if (self != state.self) {
    return state;
  }

  return state.clone()..isLoading = false;
}

SubjectListState _listResult(SubjectListState state, Action action) {
  bool self = action.payload['self'];
  if (self != state.self) {
    return state;
  }

  final Map<String, dynamic> data = action.payload;
  if (data == null) {
    return state;
  }

  int pageIndex = data['pageIndex'];
  final SubjectListState newState = state.clone()
    ..pageTotal = data['pageTotal']
    ..pageIndex = pageIndex;

  if (pageIndex == GlobalState.firstPageIndex + 1) {
    newState.items = data['items']; // reset if first page
  } else {
    newState.items.addAll(data['items']);
  }

  newState.items.forEach((item) => item.isSelectable = newState.isSelectable);
  return newState;
}

SubjectListState _deleted(SubjectListState state, Action action) {
  bool self = action.payload['self'];
  if (self != state.self) {
    return state;
  }

  String code = action.payload['index'];
  final SubjectListState newState = state.clone();
  newState.items.removeWhere((SubjectState state) => state.id == code);
  return newState;
}
